﻿using System;
using NguyenHoa.Web.App_Code;
using NguyenHoa.Services;
using NguyenHoa.Domains;
using DevExpress.Web.ASPxGridView;
using System.Web.UI.HtmlControls;

namespace NguyenHoa.Web.Admin
{
  public partial class PhotoAlbums : AdminBasePage
  {
    #region Properties
    private string m_innerError = string.Empty;

    internal override int RequiredPermission
    {
      get
      {
        return (int)FunctionList.Album;
      }
    }

    internal override void SetPermission()
    {
      if (!CanModify) btnSaveLocale.Visible = false;
    }
    #endregion

    #region Methods
    private void LoadPage()
    {
      xdsStatus.DataFile = XmlStatusFile;
      xdsLanguage.DataFile = XmlStatusFile;
    }

    private void LoadAlbum()
    {
      TList<Album> ds = new AlbumService().GetGalleryAlbum();
      gvList.DataSource = ds;
      gvList.DataBind();
    }

    private string SetShowOnHome(int albumId, bool show)
    {
      try
      {
        new AlbumService().SetShowOnHome(albumId, show);
        // GlobalCache.Instance.PhotoGallery = null;
      }
      catch (Exception ex)
      {
        WriteLog("PhotoAlbums.aspx::SetShowOnHome", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    private string SaveAlbum(int albumId, string name, string status, string description)
    {
      try
      {
        AlbumService service = new AlbumService();
        Domains.Album album = null;
        if (albumId > 0)
        {
          album = service.GetById(albumId);
          if (album == null)
          {
            return Resources.Messages.ERR0003;
          }

          album.ModifiedBy = CurrentUser.Username;
          album.ModifiedDate = DateTime.Now;
        }
        else
        {
          album = new Domains.Album();
          album.Type = AlbumType.Gallery;
          album.CreatedBy = CurrentUser.Username;
          album.CreatedDate = DateTime.Now;
        }
        album.Name = name;
        album.Status = status;

        service.Save(album);
      }
      catch (Exception ex)
      {
        WriteLog("PhotoAlbums.aspx::Save Album", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    private string DeleteAlbum(int albumId)
    {
      try
      {
        using (ConnectionScope.CreateTransaction())
        {
          AlbumLocaleService albumLocaleService = new AlbumLocaleService();
          TList<AlbumLocale> listAlbumLocale = albumLocaleService.GetByAlbumId(albumId);
          foreach (AlbumLocale albumLocale in listAlbumLocale)
          {
            albumLocaleService.Delete(albumLocale);
          }

          AlbumService aService = new AlbumService();
          Domains.Album album = aService.GetById(albumId);
          aService.Delete(albumId);
          ConnectionScope.Complete();
        }
      }
      catch (Exception ex)
      {
        WriteLog("PhotoAlbums.aspx::DeleteAlbum", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    private string LoadContent()
    {
      int languageId = -1;
      if (cbxLanguage.Value != null)
      {
        int.TryParse(cbxLanguage.Value.ToString(), out languageId);
      }
      int albumId = -1;
      if (!string.IsNullOrEmpty(hfAlbumId.Value))
      {
        int.TryParse(hfAlbumId.Value, out albumId);
      }
      TList<AlbumLocale> listAlbumLocale = new AlbumLocaleService().Find(string.Format("AlbumId = {0} AND LanguageId = {1}", albumId.ToString(), languageId.ToString()));
      if (listAlbumLocale != null && listAlbumLocale.Count > 0)
      {
        AlbumLocale albumLocale = listAlbumLocale[0];
        return string.Format("{0}|{1}", albumLocale.Name, albumLocale.Description);
      }
      return string.Empty;

    }

    private string SaveLocale()
    {
      try
      {
        int languageId = -1;
        if (cbxLanguage.Value != null)
        {
          int.TryParse(cbxLanguage.Value.ToString(), out languageId);
        }
        int albumId = -1;
        if (!string.IsNullOrEmpty(hfAlbumId.Value))
        {
          int.TryParse(hfAlbumId.Value, out albumId);
        }
        TList<AlbumLocale> listAlbumLocale = new AlbumLocaleService().Find(string.Format("AlbumId = {0} AND LanguageId = {1}", albumId.ToString(), languageId.ToString()));
        AlbumLocale albumLocale = null;
        if (listAlbumLocale != null && listAlbumLocale.Count > 0)
        {
          albumLocale = listAlbumLocale[0];
        }
        else
        {
          albumLocale = new AlbumLocale();
        }
        albumLocale.LanguageId = languageId;
        albumLocale.AlbumId = albumId;
        albumLocale.Name = txtName.Text.Trim();
        albumLocale.Description = mmNote.Text.Trim();
        new AlbumLocaleService().Save(albumLocale);
        return string.Empty;
      }
      catch (Exception ex)
      {
        WriteLog("PhotoAlbums.aspx::SaveLocale", ex);
        return Resources.Messages.ERR0004;
      }
    }
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      LoadPage();
      if (!IsCallback && !IsPostBack)
      {
        LoadAlbum();
      }

      if (gvList.IsCallback)
      {
        LoadAlbum();
      }
    }

    protected void gvList_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }

    protected void gvList_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
      int id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out id);
      m_innerError = DeleteAlbum(id);
      e.Cancel = true;
      ASPxGridView gridControl = sender as ASPxGridView;
      gridControl.CancelEdit();
      LoadAlbum();
    }

    protected void gvList_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
      string name = (e.NewValues["Name"] != null) ? e.NewValues["Name"].ToString() : string.Empty;
      string note = (e.NewValues["Description"] != null) ? e.NewValues["Description"].ToString() : string.Empty;
      string status = (e.NewValues["Status"] != null) ? e.NewValues["Status"].ToString() : VisibleStatus.Active;

      if (string.IsNullOrEmpty(name))
      {
        m_innerError = string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
      }
      else
      {
        m_innerError = SaveAlbum(-1, name, status, note);
      }
      e.Cancel = true;
      ASPxGridView gridControl = sender as ASPxGridView;
      gridControl.CancelEdit();
      LoadAlbum();
    }

    protected void gvList_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
      ASPxGridView gridControl = sender as ASPxGridView;
      int id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out id);
      string name = (e.NewValues["Name"] != null) ? e.NewValues["Name"].ToString() : string.Empty;
      string note = (e.NewValues["Description"] != null) ? e.NewValues["Description"].ToString() : string.Empty;
      string status = (e.NewValues["Status"] != null) ? e.NewValues["Status"].ToString() : VisibleStatus.Active;

      if (string.IsNullOrEmpty(name))
      {
        m_innerError = string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
      }
      else
      {
        m_innerError = SaveAlbum(id, name, status, note);
      }
      e.Cancel = true;

      gridControl.CancelEdit();
      LoadAlbum();
    }

    protected void gvList_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
    {
      if (gvList.IsNewRowEditing) return;
      if (e.DataColumn.FieldName != "ShowOnHome") return;
      ASPxGridView grid = sender as ASPxGridView;
      HtmlInputRadioButton radioBtn = grid.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "radiobtn") as HtmlInputRadioButton;
      if (radioBtn != null)
      {
        string status = (gvList.GetRowValues(e.VisibleIndex, "Status") != DBNull.Value) ? gvList.GetRowValues(e.VisibleIndex, "Status").ToString() : string.Empty;
        if (gvList.GetRowValues(e.VisibleIndex, "Id") != DBNull.Value)
        {
          int id;
          int.TryParse(gvList.GetRowValues(e.VisibleIndex, "Id").ToString(), out id);
          if (status == VisibleStatus.Disable)
            radioBtn.Visible = false;
          else
            radioBtn.Attributes.Add("onclick", "setShowOnHome('" + id + "',this.checked)");
        }
        if (gvList.GetRowValues(e.VisibleIndex, "ShowOnHome") != DBNull.Value)
        {
          bool show;
          if (gvList.GetRowValues(e.VisibleIndex, "ShowOnHome") != null)
          {
            bool.TryParse(gvList.GetRowValues(e.VisibleIndex, "ShowOnHome").ToString(), out show);
          }
        }
        //if (gvList.GetRowValues(e.VisibleIndex, "Type") != DBNull.Value &&
        //  gvList.GetRowValues(e.VisibleIndex, "Type").ToString() == AlbumType.Other)
        //{
        //  radioBtn.Disabled = false;
        //}
        //else
        //{
        //  radioBtn.Disabled = true;
        //}
      }
    }

    protected void gvList_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
      string[] para = e.Parameters.Split('|');
      if (para[0] == "ShowOnHome")
      {
        int id;
        int.TryParse(para[1], out id);
        bool show;
        bool.TryParse(para[2], out show);
        m_innerError = SetShowOnHome(id, show);
        LoadAlbum();
      }
    }

    protected void cbxCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
      string[] para = e.Parameter.Split('|');
      if (para[0] == "Load")
      {
        e.Result = string.Format("S|{0}", LoadContent());
      }
      else if (para[0] == "Save")
      {
        e.Result = SaveLocale();
      }
    }

    protected void gvList_CommandButtonInitialize(object sender, ASPxGridViewCommandButtonEventArgs e)
    {
      GridViewCommandColumnButton deleteButton = e.Column.DeleteButton;
      if (deleteButton != null && !CanDelete) deleteButton.Visible = false;
      GridViewCommandColumnButton addButton = e.Column.NewButton;

      if (!CanModify) addButton.Visible = false;
      if (!CanModify && e.Button.ButtonType == DevExpress.Web.ASPxGridView.ColumnCommandButtonType.Edit)
      {
        e.Visible = false;
      }
    }

    protected void gvList_DataBound(object sender, EventArgs e)
    {
      if (!CanModify)
      {
        (gvList.Columns["Command"] as DevExpress.Web.ASPxGridView.GridViewCommandColumn).NewButton.Visible = false;
        (gvList.Columns["Locale"] as DevExpress.Web.ASPxGridView.GridViewColumn).Visible = false;
      }
    }
    #endregion
  }
}
